package net.ck.hzq;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import net.ck.hzq.adapter.PosAllotAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import Utils.HelloWordModel;
import Utils.SharedPrefStore;
import base.BaseActivity;
import base.BaseBiz;
import dao.BackAmountOutput;
import dao.BaseOutput;
import dao.DirectionalDevicesInput;
import dialog.DirectionalAllocationDialog;
import dialog.DirectionalAllocationFalseDialog;
import dialog.DirectionalAllocationResDialog;
import event.DirectionalResEvent;
import event.LoginEvent;
import event.PosAllotEvent;
import event.SelectFlowPartnerEvent;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ui.activity.profit.biz.ProfitBiz;

public class ChooseDeviceActivity extends BaseActivity implements View.OnClickListener {

    private List<String> mSelectedDevices;
    private HashMap<String, TextView> mRangeTvMap;
    private HashMap<String, String> mBackAmountMap;
    private List<String> devices;
    private AppCompatEditText backAmountEt;
    RecyclerView deviceContainer;
    TextView selectedCount;
    private PosAllotAdapter adapter;
    private int mMaxBackAmount = 0;
    ProfitBiz profitBiz;
    SharedPrefStore store;
    private int tag = 0;

    public static void start(Activity activity, ArrayList<String> devices, int tag) {
        Intent intent = new Intent(activity, ChooseDeviceActivity.class);
        intent.putStringArrayListExtra("devices", devices);
        intent.putExtra("tag", tag);
        activity.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_choose_device;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        profitBiz = new ProfitBiz();
        mSelectedDevices = new ArrayList<>();
        mRangeTvMap = new HashMap<>();
        mBackAmountMap = new HashMap<>();
        devices = new ArrayList<>();
        if (getIntent() != null) {
            ArrayList<String> temp = getIntent().getStringArrayListExtra("devices");
            tag = getIntent().getIntExtra("tag", 1);
            if (temp != null) {
                devices.addAll(temp);
            }
        }
        deviceContainer = findViewById(R.id.device_container);
        TextView totalCount = findViewById(R.id.total_count);
        selectedCount = findViewById(R.id.selected_count);
        backAmountEt = findViewById(R.id.return_amount_et);
        totalCount.setText("终端数量：" + devices.size());
        findViewById(R.id.flow_btn).setOnClickListener(this);
        findViewById(R.id.iv_back).setOnClickListener(v -> finish());

        if (devices.size() > 0) {
            getBackAmount(devices);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void getBackAmount(List<String> sns) {
        HelloWordModel.getInstance(this).getBackAmount(sns).enqueue(new Callback<BaseOutput<BackAmountOutput>>() {
            @Override
            public void onResponse(Call<BaseOutput<BackAmountOutput>> call, Response<BaseOutput<BackAmountOutput>> response) {
                if (response.body() != null && "401".equals(response.body().result)) {
                    EventBus.getDefault().post(new LoginEvent());
                } else if (response.body() != null && response.body().data != null && response.body().data.items != null) {
                    mBackAmountMap = response.body().data.items;
                    Set<String> sns = mBackAmountMap.keySet();
                    List<String> snslist = new ArrayList<>();
                    for (String snNo : sns) {
                        snslist.add(snNo);
                        if (mRangeTvMap.get(snNo) != null) {
                            String amount = mBackAmountMap.get(snNo);
                            mMaxBackAmount = Math.max(mMaxBackAmount, Math.round(Float.valueOf(amount)));
                        }
                    }
                    adapter = new PosAllotAdapter(ChooseDeviceActivity.this, devices, snslist, mBackAmountMap);
                    deviceContainer.setLayoutManager(new LinearLayoutManager(deviceContainer.getContext()));
                    deviceContainer.setAdapter(adapter);
                    backAmountEt.setHint("当前可设置范围0-" + mMaxBackAmount + "元/台");
                }
            }

            @Override
            public void onFailure(Call<BaseOutput<BackAmountOutput>> call, Throwable t) {
                Log.d("test", t.toString());
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(PosAllotEvent event) {
        backAmountEt.setHint("当前可设置范围0-" + event.mMaxBackAmount + "元/台");
        mMaxBackAmount = event.mMaxBackAmount;
        mSelectedDevices.clear();
        mSelectedDevices.addAll(event.mSelectedDevices);
        selectedCount.setText("已选择：" + mSelectedDevices.size());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.flow_btn:
                if (mSelectedDevices.size() == 0) {
                    Toast.makeText(this, "请选择至少一台终端", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(backAmountEt.getEditableText())) {
                    Toast.makeText(this, "请设置返现金额", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (Integer.valueOf(backAmountEt.getEditableText().toString()) > mMaxBackAmount) {
                    Toast.makeText(this, "返现金额的设置范围不得高于本级返现金额", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (tag == 1) {
                    finish();
                    EventBus.getDefault().post(new SelectFlowPartnerEvent(mSelectedDevices,
                            Integer.valueOf(backAmountEt.getEditableText().toString())));
                } else {
                    showdialog();
                }
                break;
        }
    }

    private void showdialog() {
        DirectionalAllocationDialog dialog = DirectionalAllocationDialog.newInstance();
        dialog.setConfirmListener((String name, String tel) -> {


            DirectionalDevicesInput a = new DirectionalDevicesInput();
            a.backAmount = backAmountEt.getText().toString();
            a.fromId = TobuyApplication.getCustomId();
            a.toName = name;
            a.toPhone = tel;
            a.snList = new String[mSelectedDevices.size()];
            for (int i = 0; i < mSelectedDevices.size(); i++) {
                a.snList[i] = mSelectedDevices.get(i);
            }
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(a));
            profitBiz.Directionalallocation(requestBody, new BaseBiz.Callback<Boolean>() {
                @Override
                public void onSuccess(Boolean info) {
                    dialog.dismiss();
                    DirectionalAllocationResDialog dialogOK = DirectionalAllocationResDialog.newInstance();
                    dialogOK.setConfirmListener(() -> {
                        dialogOK.dismiss();
                        finish();
                        EventBus.getDefault().post(new DirectionalResEvent());
                    });
                    dialogOK.show(getSupportFragmentManager(), "");
                }

                @Override
                public void onFailure(Boolean info) {
                    dialog.dismiss();
                    DirectionalAllocationFalseDialog dialogFALSE = DirectionalAllocationFalseDialog.newInstance();
                    dialogFALSE.setConfirmListener(() -> {
                        dialogFALSE.dismiss();
                        showdialog();
                    });
                    dialogFALSE.show(getSupportFragmentManager(), "");

                }
            });
        });
        dialog.show(getSupportFragmentManager(), "");
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

}
